import { defineStore } from "pinia"
import { getCartList, deleteCartList, putCartList } from "@/api/index.js"


export const useCartStore = defineStore("useCartStore", {
  state: () => {
    return {
      cartList: [], // 购物车列表数据
    }
  },
  actions: {
    changeCartList(list) {
      this.cartList = list.map(item => {
        item.checked = true;
        return item;
      })
    },
    getCartListAsync() {
      // 发送ajax请求，获取购物车列表数据
      getCartList().then(data => {
        // console.log("--data:", data);
        this.changeCartList(data.data || [])
      })
    },
    // 删除购物车中的数据
    async deleteCartListAsync(id) {
      let res = await deleteCartList(id);
      if (res.resultCode == 200) {
        this.getCartListAsync(); // 删除成功后，重新获取数据
      }
    },
    // 购物车步进器
    async putCartListAsync(cartItemId, goodsCount) {
      let res = await putCartList(cartItemId, goodsCount);
      if (res.resultCode == 200) {
        this.getCartListAsync(); // 删除成功后，重新获取数据
      }
    },
  },
  getters: {
    cartNum() {
      return this.cartList.reduce((prev, next) => {
        return prev + next.goodsCount;
      }, 0)
    }
  }
})

